#!/bin/bash
# vim: fdm=marker fmr=[[[,]]] cms=\ #%s

usage()
{ #[[[
    echo "Usage: svrctl start | stop | status"
} #]]]

running()
{ #[[[
    local proc=$1
    local pid=$(ps -ef|grep -v grep|awk '$8~/'$proc'/ { print $2 }')
    if [[ -n $pid ]]
    then
        return 1
    fi
} #]]]

command()
{ #[[[
    case $1 in
    start)
        running httpd
        if (( $? != 0 ))
        then
            echo "httpd is running, stop first, quit..."
            return 1
        fi
        sudo $SERVER_DIR/bin/apachectl start
        sleep 2
        running httpd
        if (( $? == 0 ))
        then
            echo "httpd start fail, check..."
            return 1
        fi
        echo "httpd start succeed"
        ;;

    stop)
        sudo $SERVER_DIR/bin/apachectl stop
        sleep 2
        running httpd
        if (( $? != 0 ))
        then
            echo "httpd stop fail, check..."
            return 1
        fi
        echo "httpd stop succeed"
        ;;

    status)
        ps -ef|grep -v grep|awk '$8~/httpd/ { print }'
        ;;
    *)
        usage
        ;;
    esac
} #]]]

interact()
{ #[[[
    local option
    read -p "\
Options:
    1) start
    2) stop

    s) status
Choose: " option
    case $option in
    1) command start ;;
    2) command stop ;;
    s) command status ;;
    *) command ? ;;
    esac
} #]]]

main()
{
    local bin_dir=$(dirname $0)
    if [[ ${bin_dir:0:1} != '/' ]]
    then
        bin_dir=$PWD/$bin_dir
    fi
    SERVER_DIR=$bin_dir/..

    if (( $# == 0 ))
    then
        interact
    else
        command "$1"
    fi
}

SERVER_DIR=

main $@
exit $?
